<?php

//set error reporting
error_reporting(E_ERROR | E_WARNING);

class StockFunctions{
	
	//function to obtain an array containing dates and a prices for a stock
	//this takes a start date as parameter and fetches data up to the current date
	public static function setHistoricalQuotes($ticker, $startDate, $db){
	
		echo "in function";
	
		//declare array to hold result
		$result = array();
		
		//extract date information
		$year = substr($startDate, 0, 4);
		$month = substr($startDate, 5, 2);
		$day = substr($startDate, 8, 2);
		
		//make date yahoo finance compatible
		$month--;
		
		//declare csv file to hold data
		$csvFile = file_get_contents("http://ichart.finance.yahoo.com/table.csv?s=$ticker&c=$year&a=$month&b=$day");
		
		//now that the csv file is obtained convert to array of strings holding each line of data
		$tempResult = explode("\n", $csvFile);
		
		$numberOfRows = count($tempResult) - 1;
		
		
		//loop through each line of data and obtain the information
		for($i = 0; $i < $numberOfRows; $i++){
		
			//assign exploded result of temp array to permanent array
			$result[$i] = explode(',', $tempResult[$i+1]);
		}
		
		//we now have a 2D array of all historical data
		//add this to the database
		
		
	}
	
	//public funciton that pulls current (full) data from yahoo finance 
	public static function getCurrentStockData($ticker){
		
/************************** 
         README 
l1    =    Last    = $quote[0] 
c1    =    Change    = $quote[1] 
o    =    Opening    = $quote[2] 
h    =    High    = $quote[3] 
g    =    Low        = $quote[4] 
v    =    Volume    = $quote[5] 
***************************/ 
		$fields = 'l1c1ohgv'; 
     
    	// we use yahoo to get the quotes 
    	$host = 'http://finance.yahoo.com'; 
    	
    	// construct the url 
    	$url = $host . '/d/quotes.csv?s='. urlencode($ticker) .'&f='.$fields.''; 
    
    	// ask yahoo for the .csv file 
    	$csv = @file_get_contents($url); 
    
    	// if we get the csv file 
    	if ($csv) { 
        
    		// explode the csv file into data pices and replace the " with nothing, we dont want any "'s 
        	if ($quote = explode(',', str_replace('"', '', $csv))) { 
            
        		$quote = array_map('trim', $quote); 
            	
        		// output the quote data 
            	return $quote; 
        	} 
    	} 
	}
}

